//
//  MoAlertController.swift
//  dycommon_Example
//
//  Created by zhuxietong on 2021/1/31.
//  Copyright © 2021 CocoaPods. All rights reserved.
//

import Foundation
import UIKit
import Eelay
public enum AlertType{
    case alert
    case sheet
}
public enum PresentAnimation{
    case up
    case centerBounce
}


extension MoAlertController{
    public class appearance{
        public static var contentTextStyle:[UICss] = [.font(.systemFont(ofSize: 14)),.color(UIColor._weak),.padding([0,25,30,25])]
        public static var titleTextStyle:[UICss] = [.font(.systemFont(ofSize: 16)),.color(UIColor._foreground),.padding([20,35,20,35])]

        
        public static var confirmButton:()->ASButtonNode = {
            let bt = ASButtonNode()
            bt.ui.font(size: 15).ncolor(color: .white).buttonColor(color: ._tint).set(radius: 2, width: nil, color: nil)
            return bt
        }
        public static var cancelButton:()->ASButtonNode = {
            let bt = ASButtonNode()
            bt.ui.font(size: 15).ncolor(color: ._weak).buttonColor(color: ._tableBackground).set(radius: 2, width: nil, color: nil)
            return bt
        }
        
        public static var defaultButton:()->ASButtonNode = {
            let bt = ASButtonNode()
            bt.ui.font(size: 15).ncolor(color: ._weak).buttonColor(color: ._tableBackground).set(radius: 2, width: nil, color: nil)
            return bt
        }
    }
}

@objc public protocol MoAlertProtocol:NSObjectProtocol{
    func hidden()
}
open class MoAlertController: TableCellNodeController,MoTaskProtocol,MoAlertProtocol{
    
    public var titleTextStyle:[UICss] = appearance.titleTextStyle

    public var ID: String? = nil
    public var tellClose:((_:MoAlertController)->Void)? = nil
    public var status: MoTaskStatus = .waiting{
        didSet{
            changeStatus(status,self)
        }
    }
    public func tash() {
        status = .end
    }
    public func start() {
        status = .progress
    }
    public func end() {
        status = .end
    }
    public var type:AlertType = .alert{
        didSet{
            switch type {
            case .alert:
                animation_ = .centerBounce
            default:
                animation_ = .up
            }
        }
    }
    public var animation_:PresentAnimation = .centerBounce
    
    public var changeStatus: (MoTaskStatus, MoAlertController) -> Void = {_,_ in}{
        didSet{
            
        }
    }

    open override var LoadingPresenterBg: UIView{
        get{
            return modalView
        }
    }
    public class ModalView:RoundedView{}
    public class KeyboadAvoidBack:UIView{}
    public var keyboadFrame:CGRect = .zero

    static public var defaultStyle:[UICss] = [.size([300,300]),.offsetY(-10),.cornerRadius(8)]

    public var modalView = ModalView()
    public let titleLabel = UILabel()
    public var style:[UICss] = MoAlertController.defaultStyle
    public var closeBt = UIButton()
    public var keyboadAvoidBack = KeyboadAvoidBack()
    public weak var formController:UIViewController? = nil

    var showCloseBt_ = false
    required public init() {
        super.init()
        modalPresentationStyle = .overFullScreen
        modalTransitionStyle = .crossDissolve
        style = style + defaultStyle()
    }
    
    required public init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    public let keyboard = MoUIStatus.Keyboard(tag: "tag")
    public let touchBackground = UIControl()
    
    @objc open func hidden(){
        view.endEditing(true)
        
        switch animation_ {
        case .centerBounce:
            let animation = CAKeyframeAnimation()
            animation.keyPath = "transform.scale"
            animation.values = [1.0,1.005,0.96,0.92]
            animation.duration = 0.3
            animation.calculationMode = .cubic
            modalView.layer.add(animation, forKey: nil)
            view.alpha = 1
            weak var wself = self
            UIView.animate(withDuration: 0.3) {
                wself?.view.alpha = 0
            } completion: { (f) in
                wself?.view.alpha = 0
                if wself?.tellClose == nil{
                    wself?.end()
                }
                wself?.dismiss(animated: false, completion: nil)
            }
            if let closeAction = tellClose {
                closeAction(self)
            }
        case .up:
            
            let Y = modalView.frame.origin.y
            let bottomDistance = Sheight - Y
            view.alpha = 1
            modalView.transform = CGAffineTransform(translationX: 0, y: 0);
            UIView.beginAnimations(nil, context: nil)
            UIView.setAnimationDuration(0.25)
            UIView.setAnimationCurve(UIView.AnimationCurve(rawValue: 7)!)
            modalView.transform = CGAffineTransform(translationX: 0, y: bottomDistance);
            view.alpha = 0
            UIView.commitAnimations()
            
            co_delay(delay: 0.256) {[weak self] in
                guard let `self` = self else{return}
                if self.tellClose == nil{
                    self.end()
                }else{
                    
                }
                self.dismiss(animated: false, completion: nil)
            }
            if let closeAction = tellClose {
                closeAction(self)
            }
            
        }
    }
    
    open var modalHeight:CGFloat{
        return modalView.frame.height
    }
    public var enabelBackTouch: Bool = true
    
    open func defaultStyle() -> [UICss] {
        return [.size(CGSize(width: Swidth-60, height: Swidth-60))]
    }
    
    
 
    public var topConstrain = NSLayoutConstraint()
    open override func viewDidLoad() {
        if let c = view.setEeLays(lays: [
            [keyboadAvoidBack,[ee.height.L.R.T]]
        ]).1.last {
            topConstrain = c
        }
        
        initV()
            
            
        closeBt.alpha = 0
        view.alpha = 1
        keyboadAvoidBack.alpha = 0

        touchBackground.addTarget(self, action: #selector(finishEdit), for: .touchDown)
        modalView.backgroundColor = style.backgroundColor
        
        
//        modalView.addGestureRecognizer(UIGestureRecognizer(target: self, action: #selector(finishEdit)))
        layModal(modalView: modalView)
        closeBt.ui.padding(insets: [4])
        super.viewDidLoad()
        closeBt.ui.nimage(UIImage(_snamed: "b-delete")?.rt_tintedImage(with: ._foreground))
        closeBt.addTarget(self, action: #selector(hidden), for: .touchUpInside)

        layoutCloseBt()
        if(showCloseBt_){
            closeBt.alpha = 1
        }else{
            closeBt.alpha = 0
        }
        tableView.backgroundColor = .clear
        tableView.backgroundView?.backgroundColor = .clear
        view.backgroundColor = .clear
        keyboadAvoidBack.backgroundColor = .clear
        touchBackground.backgroundColor = .color(light: "#8888", dark: "#6666")
        switch type {
        case .alert:
            let radius = style.cornerRadius
            modalView.topLeftRadius = radius
            modalView.topRightRadius = radius
            modalView.bottomLeftRadius = radius
            modalView.bottomRightRadius = radius

        default:
            let radius = style.cornerRadius
            modalView.topLeftRadius = radius
            modalView.topRightRadius = radius
            modalView.bottomLeftRadius = 0
            modalView.bottomRightRadius = 0
        }
        

    }
    open override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
        closeBt.ui.nimage(UIImage(_snamed: "b-delete")?.rt_tintedImage(with: ._foreground))
    }
    @objc func finishEdit(){
        view.endEditing(true)
        if(enabelBackTouch){
            hidden()
        }
    }
    
    
    open func layModal(modalView:UIView){
        switch type {
        case .alert:
            keyboadAvoidBack.eelay = [
                [touchBackground,[ee.T.L.B.R]],
                [modalView,"\(style.height)",style.size.width,[ee.X],[ee.Y,style.offsetY]]
            ]
        case .sheet:
            keyboadAvoidBack.eelay = [
                [touchBackground,[ee.T.L.B.R]],
                [modalView,[ee.L.B.R],"\(style.height)"],
//                [modalView,"\(style.size.height)",style.size.width,[ee.X],[ee.Y,style.offsetY]]
            ]
        }
        
    }
    open override func layTable(tableView: UIView) {
        jo_contentView.eelay = [
            [titleLabel,[ee.T.L.R,[appearance.titleTextStyle.padding.top,28,-28]]],
            [tableView,[ee.L.B.R.safe],[titleLabel,ee.B,ee.T,10]],
        ]
        titleLabel.ui.font17.text(color: ._foreground).center.text("提示")
    }
    
    open func layoutCloseBt(){
        jo_contentView.setEeLays(lays: [
            [closeBt,[titleLabel,ee.T,-2],[ee.R,-8],"26",26],
        ])
        closeBt.ui.padding(insets: .init(top: 5, left: 5, bottom: 5, right: 5))
        
    }
    
    open override func tableNode(_ tableNode: ASTableNode, didSelectRowAt indexPath: IndexPath) {
        
        view.endEditing(true)
        super.tableNode(tableNode, didSelectRowAt: indexPath)
    }
 
    public func showAnimation() {
//        keyboadAvoidBack.backgroundColor = .systemRed
        switch animation_ {
        case .centerBounce:
            keyboadAvoidBack.alpha = 0
            weak var wself = self
            UIView.animate(withDuration: 0.34) {
                wself?.keyboadAvoidBack.alpha = 1
            } completion: { (f) in
                wself?.keyboadAvoidBack.alpha = 1
            }
            let animation = CAKeyframeAnimation()
            animation.keyPath = "transform.scale"
            animation.values = [0.8,1.005,0.99,1.0]
            animation.duration = 0.34
            animation.calculationMode = .cubic
            modalView.layer.add(animation, forKey: nil)
         
        case .up:
            
            

            let Y = modalView.frame.origin.y
            let bottomDistance = Sheight - Y
            keyboadAvoidBack.alpha = 0
            modalView.transform = CGAffineTransform(translationX: 0, y: bottomDistance);
            
            UIView.beginAnimations(nil, context: nil)
            UIView.setAnimationDuration(0.25)
            UIView.setAnimationCurve(UIView.AnimationCurve(rawValue: 7)!)
            modalView.transform = CGAffineTransform(translationX: 0, y: 0);
            self.keyboadAvoidBack.alpha = 1
            UIView.commitAnimations()

        }
       
       
        
    }
    
    @discardableResult
    open func show(at controller:UIViewController?) ->MoAlertController{
        controller?.present(self, animated: false, completion: nil)
        formController = controller
        co_delay(delay: 0.01) { [weak self] in
            self?.showAnimation()
        }
        return self

    }
}


extension MoAlertController{
//    public var sheet:Self{
//        self.type = .sheet
//
//        return self
//    }
//    public var alert:Self{
//        self.type = .alert
//        return self
//    }
    
    
    public func touchClose(_ enabel:Bool) -> Self {
        self.enabelBackTouch = enabel
        return self
    }
    public func style(_ css:[UICss])->Self{
        for one in css {
            style.update(one)
        }
        return self
    }
    public func showCloseBt()->Self{
        showCloseBt_ = true
        closeBt.alpha = 1
        return self
    }
}


